package main

import (
	"context"
	"gluenet/internal/agent"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func main() {
	if err := cmd().Execute(); err != nil {
		log.Fatalf("agent failed: %s", err)
	}
}

func cmd() *cobra.Command {
	vp := initViper()
	rootCmd := &cobra.Command{
		Use:   "agent",
		Short: "agent runs on edge side",
		Long:  "agent runs on edge side, listen on nats and execute rpcs",
		RunE: func(cmd *cobra.Command, args []string) error {
			return newServer(vp)
		},
	}

	flags := rootCmd.Flags()
	agent.InitFlag(flags)

	vp.BindPFlags(flags)
	return rootCmd
}

func initViper() *viper.Viper {
	vp := viper.New()
	return vp
}

func newServer(vp *viper.Viper) error {
	daemon := agent.NewDaemon()
	daemon.Initialize(vp)

	ctx, cancel := context.WithCancel(context.Background())
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGALRM, syscall.SIGTERM)
	go func() {
		<-sig
		cancel()
	}()

	<-ctx.Done()
	return daemon.Close()
}
